package com.yupi.picturebackend.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.picturebackend.api.aliyunai.AliYunAiApi;
import com.yupi.picturebackend.api.aliyunai.model.CreateOutPaintingTaskRequest;
import com.yupi.picturebackend.api.aliyunai.model.CreateOutPaintingTaskResponse;
import com.yupi.picturebackend.api.aliyunai.wordtopicture.model.CreateWenToPictureRequest;
import com.yupi.picturebackend.api.aliyunai.wordtopicture.model.CreateWenToPictureResponse;
import com.yupi.picturebackend.api.examine.TengXunApi;
import com.yupi.picturebackend.api.examine.model.ImageModerationResponse;
import com.yupi.picturebackend.exception.BusinessException;
import com.yupi.picturebackend.exception.ErrorCode;
import com.yupi.picturebackend.exception.ThrowUtils;
import com.yupi.picturebackend.manager.CosManager;
import com.yupi.picturebackend.manager.FileManager;
import com.yupi.picturebackend.manager.upload.FilePictureUpload;
import com.yupi.picturebackend.manager.upload.PictureUploadTemplate;
import com.yupi.picturebackend.manager.upload.UrlPictureUpload;
import com.yupi.picturebackend.model.dto.file.UploadPictureResult;
import com.yupi.picturebackend.model.dto.picture.*;
import com.yupi.picturebackend.model.entity.Picture;
import com.yupi.picturebackend.model.entity.Space;
import com.yupi.picturebackend.model.entity.User;
import com.yupi.picturebackend.model.enums.PictureReviewStatusEnum;
import com.yupi.picturebackend.model.vo.PictureVO;
import com.yupi.picturebackend.model.vo.UserVO;
import com.yupi.picturebackend.service.PictureService;
import com.yupi.picturebackend.mapper.PictureMapper;
import com.yupi.picturebackend.service.SpaceService;
import com.yupi.picturebackend.service.UserService;
import com.yupi.picturebackend.utils.ColorSimilarUtils;
import com.yupi.picturebackend.utils.ColorTransformUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author 伍立权
* @description 针对表【picture(图片)】的数据库操作Service实现
* @createDate 2025-03-27 21:25:24
*/
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
    implements PictureService{

    @Resource
    private FileManager fileManager;
    @Resource
    private UserService userService;
    @Resource
    private FilePictureUpload filePictureUpload;
    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Autowired
    private CosManager cosManager;
    @Resource
    private SpaceService spaceService;
    @Resource//编程式事务
    private TransactionTemplate transactionTemplate;
    @Resource
    private AliYunAiApi aliYunAiApi;
    @Resource
    private TengXunApi tengXunApi;

    /**
     * 上传图片含更新
     *
     * @param inputSource
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Override
    public PictureVO uploadPicture(Object inputSource, PictureUploadRequest pictureUploadRequest, User loginUser) {
        //1.参数校验
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NOT_LOGIN_ERROR);
        //校验空间是否存在
        Long spaceId = pictureUploadRequest.getSpaceId();
        //空间不为空时校验，为空是放在公共空间
        if (spaceId != null){
            Space space = spaceService.getById(spaceId);
            ThrowUtils.throwIf(space == null,ErrorCode.PARAMS_ERROR,"该空间不存在");
            Long userId = space.getUserId();
            //判断是否是空间管理员或总管理员
            if (!userId.equals(loginUser.getId()) && !userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 校验额度
            if (space.getTotalCount() >= space.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (space.getTotalSize() >= space.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }
        //2.获取请求参数是否存在pictureId
        Long pictureId = null;
        if (pictureUploadRequest.getId() != null){
            pictureId = pictureUploadRequest.getId();
        }
        //3.如果pictureId不为空，判断数据库是否存在该数据
        if (pictureId != null) {
            Picture picture = this.getById(pictureId);
            ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR, "该图片不存在");
            //仅管理员或本人操作
            if (!loginUser.getId().equals(picture.getUserId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
            // 没传 spaceId，则复用原有图片的 spaceId
            if (spaceId == null) {
                if (picture.getSpaceId() != null) {
                    spaceId = picture.getSpaceId();
                }
            } else {
                // 传了 spaceId，必须和原有图片一致
                if (ObjUtil.notEqual(spaceId, picture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.PARAMS_ERROR, "空间 id 不一致");
                }
            }
        }
        //4.按照用户 id 划分目录，并上传 ==> 按照空间划分目录
        String uploadPathPrefix;
        if (spaceId == null) {
           uploadPathPrefix = String.format("public/%s", loginUser.getId());
        } else {
            uploadPathPrefix = String.format("space/%s", spaceId);
        }

        //根据inputSource的类型，使用不同的上传方法即可
        //先设置为文件上传，如果是url上传，改就行
        PictureUploadTemplate uploadPictureTemplate = filePictureUpload;
        if (inputSource instanceof String){
            uploadPictureTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = uploadPictureTemplate.uploadPicture(inputSource, uploadPathPrefix);
        //5.构造要入库的图片信息
        Picture picture = new Picture();
        //支持外层传递图片名称
        String picName = uploadPictureResult.getPicName();
        if (pictureUploadRequest != null && StrUtil.isNotBlank(pictureUploadRequest.getPicName())){
            picName = pictureUploadRequest.getPicName();
        }
        picture.setName(picName);//图片名称
        picture.setUrl(uploadPictureResult.getUrl());//地址
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());//缩略图地址
        picture.setPicSize(uploadPictureResult.getPicSize());//大小
        picture.setPicWidth(uploadPictureResult.getPicWidth());//宽
        picture.setPicHeight(uploadPictureResult.getPicHeight());//高
        picture.setPicScale(uploadPictureResult.getPicScale());//宽高比
        picture.setPicFormat(uploadPictureResult.getPicFormat());//图片格式
        picture.setUserId(loginUser.getId());//创建用户id
        picture.setSpaceId(spaceId);//空间id
        picture.setPicColor(ColorTransformUtils.getStandardColor(uploadPictureResult.getPicColor()));
        //审核字段填充
        fillReviewParams(picture,loginUser);
        //6.如果pictureId不为空，为更新
        if (pictureId != null){
            //将图片id设置为原id
            picture.setId(pictureId);
            //设置编辑时间
            picture.setEditTime(new Date());
        }
        //7.操作数据库
        // 开启事务
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
                    boolean result = this.saveOrUpdate(picture);
                    ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR, "图片上传失败");
                    if (finalSpaceId != null) {
                        boolean update = spaceService.lambdaUpdate()
                                .eq(Space::getId, finalSpaceId)
                                .setSql("totalSize = totalSize + " + picture.getPicSize())
                                .setSql("totalCount = totalCount + 1")
                                .update();
                        ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
                    }
                    return picture;
               });
        //如果是更新，要删除原图片资源
//        if (pictureId != null){
//            this.cleanPictureFile(picture);
//        }
        //如果审核状态为拒绝，则删除临时文件
//        if (picture.getReviewStatus() == PictureReviewStatusEnum.REJECT.getValue()){
//            this.cleanPictureFile(picture);
//        }
        //8.返回图片的封装对象
        return PictureVO.objToVo(picture);
    }

    /**
     * 审核字段填充
     * @param loginUser
     * @param picture
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        if (picture.getSpaceId() != null){
            // 空间里的图片，自动过审
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("私有空间，管理员自动过审");
            return;
        }
        if (userService.isAdmin(loginUser)){
            //为管理员，自动过审
            picture.setReviewerId(loginUser.getId());
            picture.setReviewTime(new Date());
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
            picture.setReviewMessage("管理员自动过审");
        }else {
            //非管理员，进行api审核
            ImageModerationResponse imageModerationResponse = tengXunApi.checkPicture(picture.getUrl());
            String result = imageModerationResponse.getResult();
            String message = imageModerationResponse.getMessage();
            if (result.equals("0")){
                // 审核通过
                picture.setReviewerId(0L);
                picture.setReviewTime(new Date());
                picture.setReviewStatus(PictureReviewStatusEnum.PASS.getValue());
                picture.setReviewMessage("API" + message);
            }else if (result.equals("1")){
                // 违规，不通过
                picture.setReviewerId(0L);
                picture.setReviewTime(new Date());
                picture.setReviewStatus(PictureReviewStatusEnum.REJECT.getValue());
                picture.setReviewMessage("经过API审核，" + message);
            }else if (result.equals("2")){
                // 疑似违规，需要人工审核
                picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getValue());
            }else {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "图片审核失败");
            }
        }
    }

    /**
     * 构造图片的查询条件
     * @param pictureQueryRequest
     * @return
     */
    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        Long userId = pictureQueryRequest.getUserId();
        String sortField = pictureQueryRequest.getSortField();
        String sortOrder = pictureQueryRequest.getSortOrder();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        Date reviewTime = pictureQueryRequest.getReviewTime();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean isNullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startEditTime = pictureQueryRequest.getStartEditTime();
        Date endEditTime = pictureQueryRequest.getEndEditTime();
        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }
        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage),"reviewMessage",reviewMessage);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus),"reviewStatus",reviewStatus);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId),"reviewerId",reviewerId);
        queryWrapper.eq(ObjUtil.isNotEmpty(spaceId),"spaceId",spaceId);
        queryWrapper.isNull(isNullSpaceId,"spaceId");
        queryWrapper.ge(ObjUtil.isNotEmpty(startEditTime),"editTime",startEditTime);
        queryWrapper.lt(ObjUtil.isNotEmpty(endEditTime),"editTime",endEditTime);
        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }
        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortField), sortOrder.equals("ascend"), sortField);
        return queryWrapper;
    }

    /**
     * 将对象封装成Vo对象
     * @param picture
     * @param request
     * @return
     */
    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        PictureVO pictureVO = PictureVO.objToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVO userVO = userService.getUserVO(user);
            pictureVO.setUser(userVO);
        }
        return pictureVO;
    }

    /**
     * 根据分页结果获取Vo版结果
     * @param picturePage
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        //1.参数校验
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> page = new Page<>(picturePage.getCurrent(),picturePage.getSize(),picturePage.getTotal());
        //如果原分页结果为空，直接返回
        if (pictureList == null){
            return page;
        }
        //2.将Picture集合转为PictureVO集合
        List<PictureVO> pictureVOList = new ArrayList<>();
        for (Picture picture : pictureList) {
            //3.关联查询用户信息
            User user = userService.getById(picture.getUserId());
            PictureVO pictureVO = PictureVO.objToVo(picture);
            pictureVO.setUser(userService.getUserVO(user));
            pictureVOList.add(pictureVO);
        }
        //4.设置返回结果的记录
        page.setRecords(pictureVOList);
        return page;
    }

    /**
     * 判断图片是否可用
     * @param picture
     */
    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }

    /**
     * 图片审核
     */
    @Override
    public void doPictureReview(PictureReviewRequest pictureReviewRequest, User loginUser) {
        //1.参数校验
        if (pictureReviewRequest == null || pictureReviewRequest.getId() <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();
        PictureReviewStatusEnum reviewStatusEnum = PictureReviewStatusEnum.getEnumByValue(reviewStatus);
        String reviewMessage = pictureReviewRequest.getReviewMessage();
        if (id == null || reviewStatusEnum == null || PictureReviewStatusEnum.REVIEWING.equals(reviewStatusEnum)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2.判断图片是否存在
        Picture picture = this.getById(id);
        ThrowUtils.throwIf(picture == null,ErrorCode.NOT_FOUND_ERROR);
        //3.校验审核状态是否重复
        if (reviewStatus.equals(picture.getReviewStatus())){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请勿重复审核");
        }
        //4.数据库操作
        Picture updatePicture = new Picture();
        updatePicture.setId(id);
        updatePicture.setReviewStatus(reviewStatus);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewMessage(reviewMessage);
        updatePicture.setReviewTime(new Date());
        boolean updateById = this.updateById(updatePicture);
        ThrowUtils.throwIf(!updateById,ErrorCode.OPERATION_ERROR);
    }

    /**
     * 批量抓取和创建图片
     *
     * @param pictureUploadByBatchRequest
     * @param loginUser
     * @return 成功创建的图片数
     */
    @Override
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest, User loginUser) {
        //1.参数校验
        ThrowUtils.throwIf(pictureUploadByBatchRequest == null,ErrorCode.PARAMS_ERROR);
        Integer count = pictureUploadByBatchRequest.getCount();
        String searchText = pictureUploadByBatchRequest.getSearchText();
        //获取图片名称前缀，默认为搜索词
        String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
        if (StrUtil.isBlank(namePrefix)){
            namePrefix = searchText;
        }
        ThrowUtils.throwIf(count > 30,ErrorCode.PARAMS_ERROR,"单次图片数量不能超过30条");
        //2.抓取内容
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);//要抓取的地址
        Document document;
        try {
            //用Jsoup连接该地址并获取页面文档
             document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("获取页面失败",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"获取页面失败");
        }
        //3.解析内容
        Element dgControl = document.getElementsByClass("dgControl").first();//获取页面元素
        ThrowUtils.throwIf(ObjUtil.isEmpty(dgControl),ErrorCode.OPERATION_ERROR,"获取页面元素失败");
        Elements imgElementList = dgControl.select("img.mimg");//获取图片集合
        int uploadCount = 0;
        //遍历元素，依次处理上传图片
        for (Element element : imgElementList) {
            //获取图片地址
            String fileUrl = element.attr("src");
            //如果图片地址为空，跳过
            if (StrUtil.isBlank(fileUrl)){
                log.info("当前链接为空，已跳过{}",fileUrl);
                continue;
            }
            //处理图片地址，防止转义失败或和存储对象冲突
            int questionMarkIndex = fileUrl.indexOf("?");//获取问号的索引
            if (questionMarkIndex > -1){
                //截断问号后面的内容
                fileUrl = fileUrl.substring(0,questionMarkIndex);
            }
            //4.url上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            pictureUploadRequest.setFileUrl(fileUrl);
            pictureUploadRequest.setPicName(namePrefix + (uploadCount+1));
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("图片上传成功，id = {}",pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("图片上传失败",e);
                continue;
            }
            //当上传的图片数量大于目标数量，停止
            if (uploadCount >= count){
                break;
            }
        }
        return uploadCount;
    }

    /**
     * 删除图片在cos中的对象
     * @param oldPicture
     */
    @Async
    @Override
    public void cleanPictureFile(Picture oldPicture) {
        //参数校验
        if (oldPicture == null){
            return;
        }
        // 判断该图片是否被多条记录使用
        String oldPictureUrl = oldPicture.getUrl();
        LambdaQueryWrapper<Picture> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Picture::getUrl,oldPictureUrl);
        List<Picture> list = this.list(queryWrapper);
        if (list.size() > 1){
            return;
        }
        // 删除图片
        cosManager.deleteObject(oldPictureUrl);
        // 如果存在缩略图，删除缩略图
        String thumbnailUrl = oldPicture.getThumbnailUrl();
        if (StrUtil.isNotBlank(thumbnailUrl)){
            cosManager.deleteObject(thumbnailUrl);
        }

    }

    /**
     * 校验图片权限
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        Long loginUserId = loginUser.getId();
        //空间不为空时私有空间
        if (spaceId != null){
            Space space = spaceService.getById(spaceId);
            //判断是否是空间管理员或总管理员
            if (!loginUserId.equals(space.getUserId()) && !userService.isAdmin(loginUser)){
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }else {//为空是放在公共空间
            if (picture.getUserId() != null){
                if (!loginUserId.equals(picture.getUserId())){
                    throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
                }
            }
        }
    }

    /**
     * 删除图片
     * @param pictureId
     * @param loginUser
     */
    @Override
    public void deletePicture(long pictureId, User loginUser){
        //2.判断删除对象是否存在
        Picture picture = this.getById(pictureId);
        if (picture == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        //3.校验权限
        // 已改为使用注解鉴权
        //this.checkPictureAuth(loginUser,picture);
        //4.操作数据库
        // 开启事务
        Long finalSpaceId = picture.getSpaceId();
        transactionTemplate.execute(status -> {
            boolean removeById = this.removeById(picture);
            ThrowUtils.throwIf(!removeById, ErrorCode.OPERATION_ERROR, "删除图片失败");
            if (finalSpaceId != null) {
                boolean update = spaceService.lambdaUpdate()
                        .eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize - " + picture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!update, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        //5.删除图片在cos中的对象
        this.cleanPictureFile(picture);
    }

    /**
     * 编辑图片
     * @param pictureEditRequest
     * @param loginUser
     */
    @Override
    public void editPicture(PictureEditRequest pictureEditRequest, User loginUser) {
        //2.将更新对象转为实体对象
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        //3.注意将 list 转为 string，设置编辑时间
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        picture.setEditTime(new Date());
        //4.数据校验
        this.validPicture(picture);
        //5.判断图片是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        //6.校验权限
        // 已改为使用注解鉴权
        //this.checkPictureAuth(loginUser,picture);
        //公共空间的，需补充审核参数
        picture.setSpaceId(oldPicture.getSpaceId());
        if (picture.getSpaceId() == null){
            this.fillReviewParams(picture, loginUser);
        }
        //7.操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
    }

    /**
     * 获取图片相似度接近的图片列表
     * @param spaceId
     * @param picColor
     * @param loginUser
     * @return
     */
    @Override
    public List<PictureVO> searchPictureByColor(Long spaceId, String picColor, User loginUser) {
        // 参数校验
        ThrowUtils.throwIf(spaceId == null || picColor == null, ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null, ErrorCode.PARAMS_ERROR);
        // 校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null, ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无此空间权限");
        }
        // 查询该空间下所有图片（须有主色调）
        LambdaQueryWrapper<Picture> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Picture::getSpaceId, spaceId).isNotNull(Picture::getPicColor);
        List<Picture> list = this.list(queryWrapper);
        // 如没图片，返回空集合
        if (list.isEmpty()) {
            return new ArrayList<>();
        }
        // 将颜色字符转为主色调
        Color color = Color.decode(picColor);
        // 计算相似度，并排序
        List<Picture> pictureList = this.lambdaQuery()
                .eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor)
                .list();
        // 如果没有图片，直接返回空列表
        if (CollUtil.isEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 将目标颜色转为 Color 对象
        Color targetColor = Color.decode(picColor);
        // 4. 计算相似度并排序
        List<Picture> sortedPictures = pictureList.stream()
                .sorted(Comparator.comparingDouble(picture -> {
                    // 提取图片主色调
                    String hexColor = picture.getPicColor();
                    // 没有主色调的图片放到最后
                    if (StrUtil.isBlank(hexColor)) {
                        return Double.MAX_VALUE;
                    }
                    Color pictureColor = Color.decode(hexColor);
                    // 越大越相似
                    return -ColorSimilarUtils.calculateSimilarity(targetColor, pictureColor);
                }))
                // 取前 12 个
                .limit(12)
                .collect(Collectors.toList());

        // 转换为 PictureVO
        return sortedPictures.stream()
                .map(PictureVO::objToVo)
                .collect(Collectors.toList());
    }

    /**
     * 批量编辑图片
     * @param pictureEditByBatchRequest
     * @param loginUser
     */
    @Override
    public void editPictureByBath(PictureEditByBatchRequest pictureEditByBatchRequest, User loginUser) {
        // 1.获取和校验参数
        List<Long> pictureIdList = pictureEditByBatchRequest.getPictureIdList();
        List<String> tags = pictureEditByBatchRequest.getTags();
        String category = pictureEditByBatchRequest.getCategory();
        Long spaceId = pictureEditByBatchRequest.getSpaceId();
        ThrowUtils.throwIf(CollUtil.isEmpty(pictureIdList),ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(spaceId == null,ErrorCode.PARAMS_ERROR);
        ThrowUtils.throwIf(loginUser == null,ErrorCode.NOT_LOGIN_ERROR);
        // 2.校验空间权限
        Space space = spaceService.getById(spaceId);
        ThrowUtils.throwIf(space == null,ErrorCode.NOT_FOUND_ERROR,"该空间不存在");
        if (!space.getUserId().equals(loginUser.getId())){
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"没有该空间权限");
        }
        // 3.查询指定图片（仅选择需要字段）
        LambdaQueryWrapper<Picture> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Picture::getSpaceId,spaceId)
                .in(Picture::getId,pictureIdList)
                .select(Picture::getId,Picture::getSpaceId);
        List<Picture> pictureList = this.list(queryWrapper);
        if (pictureList == null){
            return;
        }
        // 4.更新分类和标签
        pictureList.forEach(picture -> {
            //将标签列表转成JSON格式
            if (CollUtil.isNotEmpty(tags)){
                picture.setTags(JSONUtil.toJsonStr(tags));
            }
            if (StrUtil.isNotBlank(category)){
                picture.setCategory(category);
            }
        });
        // 批量重命名
        String nameRule = pictureEditByBatchRequest.getNameRule() + "{序号}";
        fillPictureWithNameRule(pictureList,nameRule);
        // 5.操作数据库进行批量更新
        boolean result = this.updateBatchById(pictureList);
        ThrowUtils.throwIf(!result,ErrorCode.OPERATION_ERROR,"批量向数据库编辑失败");
    }

    /**
     * 创建ai扩图任务
     *
     * @param createPictureOutPaintingTaskRequest
     * @param loginUser
     * @return
     */
    @Override
    public CreateOutPaintingTaskResponse createPictureOutPaintingTask(CreatePictureOutPaintingTaskRequest createPictureOutPaintingTaskRequest, User loginUser) {
        // 参数校验
        ThrowUtils.throwIf(createPictureOutPaintingTaskRequest == null, ErrorCode.PARAMS_ERROR);
        // 获取图片信息
        Long pictureId = createPictureOutPaintingTaskRequest.getPictureId();
        Picture picture = this.getById(pictureId);
        ThrowUtils.throwIf(picture == null,ErrorCode.NOT_FOUND_ERROR,"图片不存在");
        // 校验权限
        // 已改为使用注解鉴权
        //checkPictureAuth(loginUser,picture);
        // 创建扩图任务
        String url = picture.getUrl();
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(url);// 图片地址
        createOutPaintingTaskRequest.setInput(input);// 输入参数
        createOutPaintingTaskRequest.setParameters(createPictureOutPaintingTaskRequest.getParameters());// 扩图参数
        // 创建任务
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    }

    /**
     * 创建ai文生图任务
     * @param createWenToPictureTaskRequest
     * @param loginUser
     * @return
     */
    @Override
    public CreateWenToPictureResponse createWenToPictureTask(CreateWenToPictureTaskRequest createWenToPictureTaskRequest, User loginUser) {
        // 参数校验
        ThrowUtils.throwIf(createWenToPictureTaskRequest == null , ErrorCode.PARAMS_ERROR);
        // 获取用户提示信息
        String prompt = createWenToPictureTaskRequest.getPrompt();
        ThrowUtils.throwIf(StrUtil.isBlank(prompt),ErrorCode.PARAMS_ERROR,"提示词不能为空");
        String negativePrompt = null;
        if (StrUtil.isNotBlank(createWenToPictureTaskRequest.getNegativePrompt())){
            negativePrompt = createWenToPictureTaskRequest.getNegativePrompt();
        }
        // 创建文生图任务
        CreateWenToPictureRequest createWenToPictureRequest = new CreateWenToPictureRequest();
        CreateWenToPictureRequest.Input input = new CreateWenToPictureRequest.Input();
        input.setPrompt(prompt);                //正向提示词
        input.setNegativePrompt(negativePrompt);//反向提示词
        createWenToPictureRequest.setInput(input);//输入参数
        createWenToPictureRequest.setParameters(createWenToPictureTaskRequest.getParameters());//生成图片参数
        // 创建任务
        return aliYunAiApi.createWenToPictureTask(createWenToPictureRequest);
    }

    /**
     * nameRule 格式：图片{序号}
     *
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList, String nameRule) {
        if (CollUtil.isEmpty(pictureList) || StrUtil.isBlank(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String pictureName = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(pictureName);
            }
        } catch (Exception e) {
            log.error("名称解析错误", e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "名称解析错误");
        }
    }
}





